
package com.apiserver.kernel.utils;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class DES {

	/**
	 * 密码长度要是8的倍数 <br>
	 * DES是一种对称加密算法,近些年使用越来越少<br>
	 * 因为DES使用56位密钥,以现代计算能力,24小时内即可被破解。
	 */
	private String key;

	private SecretKeySpec secretKeySpec;

	private Cipher cipher;

	private final String algorithm = "DES";

	private final String mode = "DES/ECB/PKCS5Padding";

	/**
	 * BCC密码取值公钥
	 * 
	 * @param desKey
	 */
	public DES(String desKey) {
		this.key = desKey.substring(desKey.length() - 30, desKey.length() - 22);
	}

	public DES() {
		super();
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	/**
	 * 加密
	 * 
	 * @param input
	 * @return
	 * @throws NoSuchPaddingException
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeyException
	 * @throws BadPaddingException
	 * @throws IllegalBlockSizeException
	 */
	public String encrypt(byte[] input) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
			IllegalBlockSizeException, BadPaddingException {
		secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);
		cipher = Cipher.getInstance(mode);
		cipher.init(1, secretKeySpec);
		
		byte[] cipherText = cipher.doFinal(input);
		byte[] output = Base64.encodeBase64(cipherText);
		return new String(output);
	}
}
